package mybatisPlugin.config;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;
import java.util.Properties;

/**
 * @author caihe
 * @date 2022/12/16 14:02
 */
@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
        }
)
public class LimitInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement)args[0];
        BoundSql boundSql = null;
        if (args.length == 4) {
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds)args[2];
            ResultHandler resultHandler = (ResultHandler)args[3];
            boundSql = ms.getBoundSql(parameter);
            
            String newSql = boundSql.getSql() + " limit 0, 5";
            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
                    newSql,
                    boundSql.getParameterMappings(), 
                    boundSql.getParameterObject());
            Executor executor = (Executor)invocation.getTarget();
            CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            List<Object> query = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, newBoundSql);
            return query;
        } else {
            boundSql = (BoundSql)args[5];
            String newSql = boundSql.getSql() + " limit 0, 5";
            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
                    newSql,
                    boundSql.getParameterMappings(),
                    boundSql.getParameterObject());
            invocation.getArgs()[5] = newBoundSql;
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
